package com.movieknight;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import com.github.savvasdalkitsis.jtmdb.BrowseOptions;
import com.github.savvasdalkitsis.jtmdb.Movie;
import com.github.savvasdalkitsis.jtmdb.BrowseOptions.ORDER;
import com.github.savvasdalkitsis.jtmdb.BrowseOptions.ORDER_BY;

import org.json.JSONException;

import android.util.Log;

// Downloads TMDB Movie Information In the Background and Caches Them

public class TMDBMovieDownloader {
	public final static int STATUS_OK = 0;
	public final static int STATUS_IO_ERROR = 1;
	public final static int STATUS_PARSE_ERROR = 2;
	
	private static final String LOG_TAG = TMDBMovieDownloader.class.getSimpleName();
	private static HashMap<Integer, Movie> movieCache;
	private static List<Movie> movieSearchResult;
	
	public TMDBMovieDownloader() {
		super();
		movieCache = new HashMap<Integer, Movie>();
	}
	
	// Get a movie. If it is not in the cache, download it.
	public static Movie get(int movieID) {
		Movie movie = null;
		
		// Check if the movie is currently in the cache.
		if(movieCache.containsKey(movieID)) {
			movie = movieCache.get(movieID);
			movieCache.remove(movieID);
		}
		
		// Check if the movie is null or has been reduced.
		if(movie == null || movie.isReduced()) {
			try {
				movie = Movie.getInfo(movieID);
			} catch (IOException e) {
				Log.w(LOG_TAG, "IO Excpetion while fetching movie ID" + movie, e);
			} catch (JSONException e) {
				Log.w(LOG_TAG, "JASONException while fetching movie ID" + movie, e);
			}
		}
		
		// If the movie cache is not null
		if(movie != null) {
			movieCache.put(movieID, movie);
		}
		
		return movie;
	}
	
	// Search for movies and put the results into a persistent field.
	public void searchMovie(String searchString) {
		movieSearchResult = null;
		BrowseOptions browseOptions = new BrowseOptions();
		browseOptions.setOrder(ORDER.DESC);
		browseOptions.setOrderBy(ORDER_BY.RATING);
		browseOptions.setQuery(searchString);
		try {
			movieSearchResult = Movie.search(searchString);
			Log.w(LOG_TAG, "" + movieSearchResult.size() + "movies for " + searchString);
		} catch (IOException e) {
			Log.w(LOG_TAG, "IOException while searching movie with " + searchString, e);
		} catch (JSONException e) {
			Log.w(LOG_TAG, "IOException while searching for movie with " + searchString, e);
		}
	}
	
	// Return the last movie search result.
	public List<Movie> getLastMovieResult() {
		return movieSearchResult;
	}
}